import axios from 'axios'
import config from './configData'
import { ElMessage,ElLoading } from 'element-plus'

let {DeviceCode,InterfaceList,WebService} = config();

let Todolist = [];  //待执行列表
let flag = true; //是否继续添加调用接口
let ExecutionList = () =>{
    for(let i = 0; i < Todolist.length; i++){
        axioscall(Todolist[i].Method,Todolist[i].Params).then(res =>{
            Todolist[i].callback(res);
        });
    }
}
//添加待执行列表
let addExecutionList = (Method,Params,callback) =>{
    Todolist.push({Method,Params,callback})
}
//重新获取authkey
function getAutheky(){
    return new Promise((r,j)=>{
        let par = {
            UserName:'mamaclassMeiChibackstage',
            Password:'meichi@20230406!',
            DeviceCode,
            ExtParams:'',
        }
        axioscall('UserLogin.Login',par).then(res =>{
            flag = true;
            sessionStorage.setItem('AuthKey',res.AuthKey);
            r(res.AuthKey);
        })
    })
}
let loading = null;
function axioscall(Method,Params,headers){
    if(!loading){
        loading = ElLoading.service({
            lock: true,
            text: '加载中...',
        })
    }
    return myAxios(Method,Params,headers)
}


function myAxios(Method,Params,headers){
    return new Promise((r,j) =>{
        let par = {
            Sequence:InterfaceList.indexOf(Method),
            Method,
            DeviceCode,
            AuthKey:sessionStorage.getItem('AuthKey') || '',
            Params:JSON.stringify(Params),
            CompressFlag:'N'
        }
        let data = {
            RequestPack:JSON.stringify(par)
        }
        axios({url:'/apis',method:'post',data:data,headers:headers || {'Content-Type': 'application/x-www-form-urlencoded',},}).then(async res =>{
            res =  res.data = JSON.parse(res.request.responseXML.documentElement.innerHTML);
            if(loading){
                loading.close();
                loading = null;
            }
            if(res.Return >= 0){
                if(res.Result){
                    r(JSON.parse(res.Result));
                    return
                }
                r(res.Result);
            }else if(res.Return == -100){
                addExecutionList(Method,Params,r);
                if(flag){
                    flag = false;
                    let AuthKey = await getAutheky();
                    ExecutionList();
                }
            }else{
                ElMessage.error(res.ReturnInfo);
            }
        }).catch(err =>{
            console.log(err,'111111111111');
            if(loading){
                loading.close();
                loading = null;
            }
        })
    })
}

export default function(){
    return {
        getAutheky,
        axioscall,
        myAxios
    }
}
